package cn.yj.relay.core.controller;


import cn.yj.relay.common.utils.DateTimeUtils;
import cn.yj.relay.common.utils.StringUtils;
import cn.yj.relay.core.entity.Admin;
import cn.yj.relay.core.entity.BaseEntity;
import cn.yj.relay.core.service.IAdminService;
import cn.yj.relay.core.service.ITaskService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import javafx.scene.transform.Transform;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.yj.relay.common.web.R;
import cn.yj.relay.common.exception.MyException;
import cn.yj.relay.common.web.BaseController;

import java.util.*;

import org.springframework.web.bind.annotation.*;
import cn.yj.relay.core.entity.Emp;
import cn.yj.relay.core.service.IEmpService;
import org.springframework.stereotype.Controller;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import org.springframework.ui.Model;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 永健
 * @since 2020-03-03 17:41
 */

@RestController
@RequestMapping("/emp")
public class EmpController extends BaseController<Emp>
{
// 前面的和现在的代码，绝对不是一个人写的，他肯定是拷贝的
    @Autowired
    IEmpService thisService;

    @Autowired
    IAdminService iAdminService;

    @Autowired
    ITaskService iTaskService;

    @GetMapping("/list")
    public R list(@RequestParam Map<String, Object> param)
    {
        return success(thisService.findList(param, page()));
    }

    @GetMapping("/empList")
    public R list()
    {
        return success(thisService.list());
    }

    @PostMapping("/save")
    public R insertSave(@Valid Emp emp)
    {
        String phone = emp.getPhone();
        int count = thisService.count(new QueryWrapper<Emp>().lambda().eq(Emp::getPhone, phone));
        if (count > 0)
        {
            throw new MyException("手机号已经存在");
        }
        return result(thisService.save(emp));
    }


    @GetMapping("/bonus")
    public R bonus(String empName)
    {
        // 获取当前月
        Calendar cal = Calendar.getInstance();
        int month = cal.get(Calendar.MONTH) + 1;

        String role = getRole();

        List<Emp> list = new ArrayList<>();
        LambdaQueryWrapper<Emp> select = new QueryWrapper<Emp>().lambda().select(Emp::getId, Emp::getName, Emp::getPhone);
        if (role.equals("emp"))
        {
            select.eq(Emp::getId, getLoginEmp().getId());

            if (StringUtils.isNotBlank(empName))
            {

                if (!empName.equals(getLoginEmp().getName()))
                {
                    return error("不允许搜索他人的数据");
                }
            }
        }

        if (StringUtils.isNotBlank(empName))
        {
            select.like(Emp::getName, empName);
        }

        list = thisService.list(select);

        Map<String, Object> map = getMap();

        List<Object> objects = new ArrayList<>();
        map.put("users", objects);
        list.forEach(emp -> {
            Integer id = emp.getId();

            Map<String, Object> userMap = getMap();
            userMap.put("empName", emp.getName());
            userMap.put("empPhone", emp.getPhone());
            List<Map<String, Object>> maps = new ArrayList<>();

            double bonus = 0;
            for (int i = 1; i <= 12; i++)
            {
                double monthbonus = 0;
                Map<String, Object> monthMap = getMap();
                if (i <= month)
                {
                    // 统计当前月的数据
                    List<Map<String, Object>> mapList = iTaskService.sumEmpRoYalMoney(DateTimeUtils.getFirstDayOfMonth(i), DateTimeUtils.getLastDayOfMonth(i), id);

                    for (Map<String, Object> m : mapList)
                    {
                        Object money = m.get("royaltyMoney");
                        if (money != null)
                        {
                            Double aDouble = Double.valueOf(money.toString());
                            monthbonus += aDouble;
                            bonus += aDouble;
                        }
                    }
                }
                monthMap.put(i + "月", monthbonus);
                userMap.put(i + "月", monthbonus);
                maps.add(monthMap);
            }
            userMap.put("months", maps);
            userMap.put("bonus", bonus);

            objects.add(userMap);
            map.put("users", objects);
        });
        return success(map);
    }

    public static void main(String[] args)
    {
        Calendar cal = Calendar.getInstance();
        int day = cal.get(Calendar.DATE);
        int month = cal.get(Calendar.MONTH) + 1;
        System.out.println(month);

    }


    @PutMapping("/update")
    public R editSave(Emp emp)
    {
        String phone = emp.getPhone();
        Emp one = thisService.getOne(new QueryWrapper<Emp>().lambda().eq(Emp::getPhone, phone));
        if (!emp.getId().equals(one.getId()))
        {
            throw new MyException("手机号已经存在");
        }
        return result(thisService.updateById(emp));
    }

    @GetMapping("/myInfo")
    public R myInfo()
    {
        Emp emp = getLoginEmp();
        Map<String, Object> map = new HashMap<>();
        map.put("id", emp.getId());
        map.put("name", emp.getName());
        map.put("role", "emp");
        map.put("phone", emp.getPhone());
        map.put("password", emp.getPassword());
        return success(map);
    }


    @GetMapping("/selectById/{id}")
    public R selectById(@PathVariable("id") String id)
    {
        return success(thisService.getById(id));
    }


    @DeleteMapping("/remove/{ids}")
    public R delete(@PathVariable("ids") List<Integer> ids)
    {
        return result(thisService.removeByIds(ids));
    }


    @PutMapping("updatePwd")
    public R updadePwd(@RequestParam("oldPwd") String oldPwd, @RequestParam("password") String pwd)
    {
        String role = getRole();
        if (role.equals("admin"))
        {
            Admin emp = getLoginAdmin();
            String password = emp.getPassword();
            if (!password.equals(oldPwd))
            {
                throw new MyException("旧密码不对");
            }
            emp.setToken(UUID.randomUUID().toString());
            emp.setPassword(pwd);
            return success(iAdminService.saveOrUpdate(emp));
        }
        Emp emp = getLoginEmp();
        String password = emp.getPassword();
        if (!password.equals(oldPwd))
        {
            throw new MyException("旧密码不对");
        }
        emp.setToken(UUID.randomUUID().toString());
        emp.setPassword(pwd);
        return result(thisService.saveOrUpdate(emp));
    }
}

